package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求的编码，按照何种格式来理解请求
        req.setCharacterEncoding("utf8");
        // 设置响应的编码，按照何种格式来构造响应
        resp.setContentType("text/html;charset=utf8");

        // 1,读取请求参数中的username和password
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 2,判断username和password字段是否缺失
        if(username == null || username.equals("") || password == null || password.equals("")){
            // 登录失败
            String html = "<h3>登录失败！缺少 username 或者 password 字段 </h3>";
            resp.getWriter().write(html);
            return;
        }
        //3，读取user表，判断username是否存在，若存在，密码是否匹配
        UserDao userDao = new UserDao();
        User user = userDao.selectByUsername(username);
        if(user == null){
            String html = "<h3>登录失败！username 或 password 输入错误，请重新输入！</h3>";
            resp.getWriter().write(html);
            return;
        }
        if(!password.equals(user.getPassword())){
            String html = "<h3>登录失败！username 或 password 输入错误，请重新输入！</h3>";
            resp.getWriter().write(html);
            return;
        }

        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //检测当前用户是否登录状态
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession(false);
        if(session == null){
            User user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
